﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using BitMiracle.Docotic.Pdf;
//using ScintillaNet;
using System.Xml;
using Word = Microsoft.Office.Interop.Word;

namespace BussinesLogic
{
    public class Functions
    {

        public static int NumeroLinea;
        public static string selectFile()
        {
            OpenFileDialog bDialog = new OpenFileDialog();

            bDialog.Title = "Open Word or Text File";

            bDialog.Filter = "Text Files|*.doc;*.docx";

            bDialog.InitialDirectory = @"C:\";
            string File = "";

            if (bDialog.ShowDialog() == DialogResult.OK)
                File = bDialog.FileName.ToString();
            return File;
        }

        public static string getpath()
        {
            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6) + "\\tempFiles\\";
            try
            {
                // If the directory doesn't exist, create it.
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(path+e.ToString());
            }
            return path;
        }

        public static ArrayList lineReader(string source)
        {
            String line;

            ArrayList lista = new ArrayList();

            try
            {
                //Pass the file path and file name to the StreamReader constructor
                StreamReader sr = new StreamReader(source);

                //Read the first line of text
                line = sr.ReadLine();

                //Continue to read until you reach end of file
                while (line != null)
                {
                    //write the lie to console window
                    Console.WriteLine(line);
                    //Read the next line
                    line = sr.ReadLine();
                    lista.Add(line);
                }

                //close the file
                sr.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show("Exception: " + e.Message);
            }
            File.Delete(source);
            return lista;
        }

        public static string SplitPdfByPages(string sourcePdf, int numOfPages, string path, string baseNameOutPdf, int docid, string NoExpediente, string CodDocumento, string tipo)
        {
            NumeroLinea = 1;
            PdfReader reader;
            iTextSharp.text.Document doc;
            iTextSharp.text.pdf.PdfCopy pdfCpy;
            iTextSharp.text.pdf.PdfImportedPage page;
            string strxml = "";
            int pageCount = 0;
            try
            {

                reader = new PdfReader(sourcePdf);
                pageCount = reader.NumberOfPages;

                if (pageCount < 2)
                {
                    MessageBox.Show("No se puede devidir un documento de " + pageCount + " paginas.");
                }
                else
                {
                    string ext = baseNameOutPdf;
                    string outfile = String.Empty;
                    int n = pageCount / numOfPages;
                    int currentPage = 1;
                    for (int i = 1; i <= n; i++)
                    {
                        outfile = Convert.ToString(path + ext + "_" + i.ToString() + ".pdf");
                        doc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                        pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new FileStream(outfile, FileMode.Create));
                        doc.Open();
                        if (i < n)
                        {
                            for (int j = 1; j <= numOfPages; j++)
                            {
                                page = pdfCpy.GetImportedPage(reader, currentPage);
                                pdfCpy.AddPage(page);
                                currentPage += 1;
                            }
                        }
                        else
                        {
                            for (int j = currentPage; j <= pageCount; j++)
                            {
                                page = pdfCpy.GetImportedPage(reader, j);
                                pdfCpy.AddPage(page);
                            }
                        }
                        doc.Close();
                        strxml+=ReadPdfFile(outfile, i, docid);
                        File.Delete(outfile);
                    }

                }
                reader.Close();
                

            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            strxml = "<documento docid='" + docid + "' PageNo='" + pageCount.ToString() + "' NoExpediente='" + NoExpediente + "' CodDocumento='" + CodDocumento + "' Tipo='" + tipo + "'>" + strxml + "</documento>";
            return strxml;
        }

        public static string ReadPdfFile(object Filename, int pageno, int docid)
        {
            PdfReader reader = new PdfReader(Filename.ToString());
            int pageCount = reader.NumberOfPages;
            DateTime now = DateTime.Now;
            string path = getpath();
            object Target = path + "\\" + now.Ticks.ToString();

            //for (int j = 0; j < pageCount; j++)
            //{
            BitMiracle.Docotic.Pdf.PdfDocument pdf = new BitMiracle.Docotic.Pdf.PdfDocument(Filename.ToString());
            // Extract plain text from first page
            string tempFile = Target.ToString() + "_" + pageno.ToString() + ".txt";
            using (StreamWriter writer = new StreamWriter(tempFile))
                writer.Write(pdf.Pages[0].GetText());
            pdf.Dispose();
            string strxml = XmlBuilder(tempFile, pageno, docid);
            return strxml;
            //}

        }

        public static string XmlBuilder(string source, int pagina, int docid)
        {
            ArrayList lista = lineReader(source);

            string xmlstr = "<pagina no='" + pagina.ToString() + "' Lineas='" + lista.Count + "' Tipo='" + "1" + "'>";

            
            foreach (string s in lista)
            {
                xmlstr += "<linea no='" + NumeroLinea.ToString() + "' ";
                xmlstr += "text ='" + System.Web.HttpUtility.HtmlEncode(s) + "' />";
                NumeroLinea++;
            }
            xmlstr += "</pagina>";
            return xmlstr;
        }

        public static string XmlEscape(string unescaped) 
        { 
            XmlDocument doc = new XmlDocument(); 
            var node = doc.CreateElement("root"); 
            node.InnerText = unescaped; 
            return node.InnerXml; 
        }
        public static string XmlUnescape(string escaped) 
        { 
            XmlDocument doc = new XmlDocument(); 
            var node = doc.CreateElement("root"); 
            node.InnerXml = escaped; 
            return node.InnerText; 
        }

    }
}
